/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.thienloc.omap.converter;

import com.thienloc.omap.entity.OmapRole;
import com.thienloc.omap.session.OmapRoleFacade;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 *
 * @author GiangLT
 */
//@FacesConverter(forClass = OmapRole.class, value = "omapRoleConverter")
@ManagedBean
@ViewScoped
public class OmapRoleConverter implements Converter {

    @EJB
    private OmapRoleFacade facade;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (value.trim().equals("")) {
            return null;
        } else {
            try {
                return facade.findByRoleName(value);
            } catch (Exception ex) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid role"));
            }
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return ((OmapRole) value).getRoleName();
        }
    }
}
